<?php
class ClaycodeAjaxRouting
{
	private static $o_instance;
	private $o_configuration;
	private $s_error;
	private $arr_serviceConfig;
	private $s_handlerClassName;
	private $s_handlerAction;
	private $o_serviceClass;
	
	public function __construct()
	{
		$this->s_handlerClassName = null;
		$this->s_handlerAction = null;
		$this->s_error = 'error happened';
		$this->o_configuration = Claycode_configuration::getInstance();
	}
	
	public function getServiceConfig()
	{
		return $this->arr_serviceConfig;
	}
	
	public static function getInstance()
	{
		if(!isset(self::$o_instance) ||  self::$o_instance == null) {
			self::$o_instance = new ClaycodeAjaxRouting();
		}
		return self::$o_instance;
	}
	
	public function routeRequest()
	{
		//check if you are browsing safe first
		if(SessionHandler::getInstance()->browsingSafe() == true){
			if($_SERVER['REQUEST_METHOD'] == 'GET'){
				$arr_request = $_GET;
			}else{
				$arr_request = $_POST;
			}
			
			$this->handleRequest($arr_request);
		}
	}
	
	private function handleRequest($arr_request)
	{
		$s_appRequestKey  = $this->o_configuration->getServiceRequestParam();
		//get the current application
		try {
			if(isset($_GET[$s_appRequestKey])){
				//fw_util_outputJson(array($_GET[$s_appRequestKey], $_GET['req']));
				if($this->o_configuration->getServiceConfig($_GET[$s_appRequestKey]) != false){
					//service found
					$this->arr_serviceConfig = $this->o_configuration->getServiceConfig($_GET[$s_appRequestKey]);
					//class name
					$this->s_handlerClassName = $this->arr_serviceConfig['handler'];
					//method name
					$s_handlerAction = $this->arr_serviceConfig['action'];
					//get the file to load
					$s_file = C_FW_customPackage . 'services/' . $this->s_handlerClassName . '.php';
			
					//check if the file is readable
					if(is_readable($s_file)) {
						//include it
						include $s_file;
						
						//check if the method is callable
						if (is_callable(array($this->s_handlerClassName, $s_handlerAction))) {
							$this->o_serviceClass = new $this->s_handlerClassName();
							$this->o_serviceClass->$s_handlerAction($arr_request);
						}else{
							$this->o_serviceClass = new $this->s_handlerClassName();
							$this->o_serviceClass->runService();
						}
					}else{
						throw new Exception('service not found');
					}
				}else{
					throw new Exception('request is invalid');
				}
			}else{
				throw new Exception('incorrect entry key');
			}
		} catch (Exception $e) {
			//die($e->getMessage());
			fw_util_outputJson(array('error_in_input'=>$arr_request, 'message'=>$e->getMessage()));
		}
		
		
	}
	
	
}
?>